package com.webas.core.auth;

import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.Session;

import com.webas.api.auth.AuthenticationException;
import com.webas.api.auth.User;
import com.webas.api.auth.services.Authenticator;
import com.webas.api.dao.IDaoService;
import com.webas.api.dao.QueryParameters;
/**
 * 
 * @author tkhasano
 *
 */
public class BasicAuthenticator implements Authenticator
{
	public static final String AUTH_TOKEN = "authToken";
	
    @Inject
    private IDaoService daoService;
    
    @Inject
    private Request request;

    public void login(String username, String password) throws AuthenticationException {
    	User user = daoService.findUniqueWithNamedQuery(User.BY_CREDENTIALS,
        		QueryParameters.with("username", username)
        						.and("password", password).parameters());
        if (user == null) {
        	throw new AuthenticationException("The user doesn't exist");
        }
        request.getSession(true).setAttribute(AUTH_TOKEN, user);
    }

    public boolean isLoggedIn() {
    	Session session = request.getSession(false);    	
        if (session != null) {
        	return session.getAttribute(AUTH_TOKEN) != null;
        }        
        return false;
    }

    public void logout() {
        Session session = request.getSession(false);
        if (session != null) {
            session.setAttribute(AUTH_TOKEN, null);
            session.invalidate();
        }
    }

    public User getLoggedUser() {
        User user = null;
        if (isLoggedIn()) {
            user = (User) request.getSession(true).getAttribute(AUTH_TOKEN);
        } else {
            throw new IllegalStateException("The user is not logged ! ");
        }
        return user;
    }

	@Override
	public void login(String token) throws AuthenticationException {
		User user = null;
		Session session = request.getSession(false);
        if (session != null) {
            user = (User) session.getAttribute(token);
        }        
        if (user == null) {
        	throw new AuthenticationException("The user doeSsn't exist");
        }
        request.getSession(true).setAttribute(token, user);
	}

	@Override
	public void login() throws AuthenticationException {
		this.login("Anonymous");
	}
}
